package com.jqkb.service.util;

import android.provider.Settings;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jqkb.TheApplication;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class SimpleApi {
    public static Retrofit newInstance() {
        return newInstance(3000, 0, 0);
    }

    public static Retrofit newInstance(long connectTimeout, long readTimeout, long writeTimeout) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        Request request = original.newBuilder()
                                .header("device", TheApplication.getDeviceId())
                                .header("user-agent", TheApplication.getUserAgent())
                                .header("loginKey", TheApplication.getCurrentUser() != null ? TheApplication.getCurrentUser().getLoginKey() : "")
                                .method(original.method(), original.body())
                                .build();

                        return chain.proceed(request);
                    }
                })
                .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
                .writeTimeout(writeTimeout, TimeUnit.MILLISECONDS)
                .build();

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(TheApplication.getServer());
        builder.client(okHttpClient);

        Retrofit retrofit = builder.build();
        return retrofit;
    }


    public static <T> T create(Class<T> bean) {
        return newInstance().create(bean);

    }
}
